<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="45%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="100px"
             status-icon>

      <el-form-item v-if="dialogMode === 0 || dialogMode === 2" label="用户编号：">
        <el-input v-model="formData.user_id" readonly/>
      </el-form-item>

      <el-form-item v-if="dialogMode === 1" label="用户账号：" prop="account">
        <SelectRemote v-model="formData.account" api-url="/search/user/list" placeholder="请选择用户" style="margin-top: 3px" @change="handleUserSelectChange"/>
      </el-form-item>

      <el-form-item label="代理状态：" prop="status">
        <DictSelect v-if="!readonly" v-model="formData.status"
                    :clearable="false"
                    :show-default="false"
                    dict-type="agent_status"
                    placeholder="请选择代理状态"
                    style="padding-right: 10px;width: 50%"/>
        <DictTag v-if="formData.status >= 0" v-model="formData.status" :circle="false" dict-type="agent_status"/>
      </el-form-item>

      <el-form-item label="代理区域：" prop="region_full_name">
        <TreeSelect ref="regionTreeRef"
                    v-model="formData.region_full_name"
                    :tree-data="regionOptions"
                    title="请选择代理区域"
                    tree-key="code"
                    @selectChange="handleChangeRegion"/>
      </el-form-item>

      <el-form-item label="姓名：" prop="name">
        <el-input v-model="formData.name" :readonly="readonly" placeholder="请输入姓名"/>
      </el-form-item>

      <el-form-item label="身份证号：" prop="identity_card_no">
        <el-input v-model="formData.identity_card_no" :readonly="readonly" placeholder="请输入身份证号"/>
      </el-form-item>

      <el-form-item label="联系电话：" prop="contact_phone">
        <el-input v-model="formData.contact_phone" :readonly="readonly" placeholder="请输入联系电话"/>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['agent:agent:create', 'agent:agent:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, nextTick, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { agentInfo, agentSaveOrUpdate, RegionAgent } from '@/api/api-agent.ts';
import { TreeSelect } from '@/components/tree-select';
import addressList from '@/utils/address.ts';
import { DictSelect } from '@/components/dict-select';
import { DictTag } from '@/components/dict-tag';
import { SelectRemote } from '@/components/other';

defineOptions({name: 'agent-config-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: RegionAgent = <RegionAgent>{id: 0, status: 10};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  account: [{required: true, message: '归属用户不能为空', trigger: 'blur'}],
  status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
  region_full_name: [{required: true, message: '代理区域不能为空', trigger: 'blur'}],
  name: [{required: true, message: '姓名不能为空', trigger: 'blur'}],
  contact_phone: [{required: true, message: '联系电话不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

const account = ref();

/** 打开弹窗 */
const open = async (mode: number, uid?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '区域代理';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (uid) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await agentInfo(uid)
      formData.value = data;
      handleRegionSet();
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    agentSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  account.value = '';
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 地区*/
const regionTreeRef = ref();
const regionOptions = addressList;
const handleChangeRegion = (item?: any) => {
  formData.value.region_code = item;
};

const handleRegionSet = () => {
  nextTick(() => {
    regionTreeRef.value?.handleSetCurrentNode(formData.value.region_code)
  });
}

/** 处理用户改变 */
const handleUserSelectChange = async (value: any) => {
  if (value && value.id > 0) {
    formData.value.user_id = value.id;
    formData.value.contact_phone = value.label1;
  } else {
    account.value = undefined;
    formData.value.user_id = 0;
  }
}
</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select,
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
